package com.rdc.jiajiadictionary.dailysentence;

import android.media.MediaPlayer;


import com.rdc.jiajiadictionary.base.BasePresenter;
import com.rdc.jiajiadictionary.bean.DailySentence;
import com.rdc.jiajiadictionary.data.getdailysentence.DailySentenceModel;
import com.rdc.jiajiadictionary.data.getdailysentence.DailySentenceModelInterface;

import java.io.IOException;


public class DailySentencePresenter implements BasePresenter {

    private DailySentenceViewInterface mDailySentenceViewInterface;//view层引用
    private DailySentenceModelInterface mDailySentenceModelInterface ;//model层引用
    private DailySentence mDailySentence;
    private MediaPlayer mediaPlayer = null;


    public DailySentencePresenter(){

    }

    /**
     * 构造方法，传入一个view层接口，进行view层和presenter层的双向绑定，并创建model层对象的引用
     * @param dailySentenceViewInterface
     */
    public DailySentencePresenter(DailySentenceViewInterface dailySentenceViewInterface){
        mDailySentenceViewInterface = dailySentenceViewInterface;
        mDailySentenceViewInterface.setPresenter(this);
        mDailySentenceModelInterface  = new DailySentenceModel();
    }

    /**
     * 实现model层接口，从model层获取每日语句数据并通过view层引用调用view层方法进行ui更新
     */
    public void getDailySentence(){
        mDailySentenceModelInterface.getSentenceFromApi(new DailySentenceModel.GetSentenceCallBack() {
            @Override
            public void onComplete(DailySentence dailySentence) {
                mDailySentence = dailySentence;
                mDailySentenceViewInterface.setData(mDailySentence.getFullDrawable());
            }
            @Override
            public void onDataNotAvailable() {

            }
        });
    }

    /**
     * 开始获取每日一句
     */
    @Override
    public void start() {
        getDailySentence();
    }


    /**
     * 提供播放句子方法给view层调用
     */
    public void play(){

        if(null == mediaPlayer){
            mediaPlayer = new MediaPlayer();
            mDailySentenceViewInterface.toast("正在获取网络发音");
        }
        if(mediaPlayer.isPlaying()){
        }else {
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(mDailySentence.getAudioUrl());
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
